﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using ZXing;
using ZXing.QrCode;
using ZXing.Common;

namespace WindowsFormsAppOpenFile
{
    class TablePrinter 
    {
    private PrintDocument _printDocument = new PrintDocument();
    private string[,] _tableData;
    private int _rowCount;
    private int _colCount;
    private string _qrCodeText;
    // 构造函数接收表格数据
    public TablePrinter(string[,] tableData, string qrCodeText = null,string printerName = null)
    {
        _tableData = tableData;
        _rowCount = tableData.GetLength(0);
        _colCount = tableData.GetLength(1);
        _qrCodeText = qrCodeText;
        _printDocument.PrintPage += PrintDocument_PrintPage;
        SetPaperSize(GValues.Paper_SizeLength, GValues.Paper_SizeWidth); // 设置70mm*60mm纸张
        if (!string.IsNullOrEmpty(printerName))
        {
            _printDocument.PrinterSettings.PrinterName = printerName;
            
        }
    }
    // 设置纸张大小（毫米为单位）
    private void SetPaperSize(float widthMM, float heightMM)
    {
        // 1毫米 = 3.93701百分之一英寸
        var width = (int)(widthMM * 3.93701);
        var height = (int)(heightMM * 3.93701);

        _printDocument.DefaultPageSettings.PaperSize = new PaperSize(
            "Custom70x60mm", width, height);
        _printDocument.DefaultPageSettings.Margins = new Margins(5, 5, 5, 5);
        _printDocument.OriginAtMargins = true;
       
    }
    public Bitmap GenerateQRCode(string text, int width, int height)
    {
        var barcodeWriter = new BarcodeWriter
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new QrCodeEncodingOptions
            {
                Width = width,
                Height = height,
                Margin = 1
            }
        };

        return barcodeWriter.Write(text);
    }
    // 设置打印机名称
    public string PrinterName
    {
        get {return _printDocument.PrinterSettings.PrinterName;}
        set {_printDocument.PrinterSettings.PrinterName = value;}
    }

    // 直接打印
    public void Print()
    {
        if (!_printDocument.PrinterSettings.IsValid)
            throw new InvalidOperationException("无效的打印机设置");

        _printDocument.Print();
    }

    // 打印预览
    public void PrintPreview()
    {
        using (var previewDialog = new PrintPreviewDialog())
        {
            previewDialog.Document = _printDocument;
            previewDialog.ShowDialog(); // 此处仍需Windows环境支持，但不依赖Form继承
        }
    }

    private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
    {
        //Graphics g = e.Graphics;
        //float marginLeft = e.MarginBounds.Left;
        //float marginTop = e.MarginBounds.Top;
        //float tableWidth = e.MarginBounds.Width;
        //float rowHeight = e.MarginBounds.Height / 8f; // 8行均分高度
        //float[] columnWidths = CalculateColumnWidths(tableWidth);

        //DrawTable(g, marginLeft, marginTop, rowHeight, columnWidths);
        //e.HasMorePages = false;




        Graphics g = e.Graphics;
        float marginLeft = e.MarginBounds.Left;
        float marginTop = e.MarginBounds.Top;
        // 增加额外边距(10单位)，解决右边界和底边界问题
        float extraMargin = 10;
        float tableWidth = e.MarginBounds.Width - extraMargin; // 左右各预留空间
        float totalRowHeight = (e.MarginBounds.Height - extraMargin) / 8f; // 上下各预留空间
        float[] columnWidths = CalculateColumnWidths(tableWidth);

        // 调整起始位置，向右和向下各移动extraMargin单位
        DrawTable(g, marginLeft, marginTop, totalRowHeight, columnWidths);
        e.HasMorePages = false;

        //Graphics g = e.Graphics;
        //float marginLeft = e.MarginBounds.Left;
        //float marginTop = e.MarginBounds.Top;
        //float extraMargin = 10;

        //// 确保表格宽度不为负
        //float tableWidth = e.MarginBounds.Width - extraMargin * 2;
        //tableWidth = Math.Max(tableWidth, 10); // 设置最小宽度

        //// 确保行高不为负
        //float totalRowHeight = (e.MarginBounds.Height - extraMargin * 2) / 8f;
        //totalRowHeight = Math.Max(totalRowHeight, 10); // 设置最小行高

        //float[] columnWidths = CalculateColumnWidths(tableWidth);
        //DrawTable(g, marginLeft + extraMargin, marginTop + extraMargin, totalRowHeight, columnWidths);
        //e.HasMorePages = false;
    }

    private float[] CalculateColumnWidths(float totalWidth)
    {
        // 根据合并规则计算列宽（第一列占20%，其余列平均分配）
        //float[] widths = new float[_colCount];
        //widths[0] = totalWidth * 0.2f;
        //float remainingWidth = totalWidth * 0.8f;

        //for (int i = 1; i < _colCount; i++)
        //    widths[i] = remainingWidth / (_colCount - 1);

        //return widths;
        return new[] { totalWidth * 0.2f, totalWidth * 0.35f, totalWidth * 0.25f, totalWidth * 0.2f };
    }

    private void DrawTable(Graphics g, float x, float y, float rowHeight, float[] columnWidths)
    {
        //using (Font font = new Font("SimSun", 10))
        //using (Brush brush = Brushes.Black)
        //using (Pen pen = new Pen(Color.Black, 1))
        //{
        //    for (int row = 0; row < _rowCount; row++)
        //    {
        //        float currentX = x;
        //        DrawRow(g, currentX, y, rowHeight, columnWidths, row, font, brush, pen);
        //        y += rowHeight;
        //    }
        //}
        using (Font font = new Font("Microsoft YaHei", 10))
        using (Brush brush = Brushes.Black)
        using (Pen pen = new Pen(Color.Black, 0.5f))
        {
            for (int row = 0; row < _rowCount; row++)
            {
                float currentX = x;
                DrawRow(g, currentX, y, rowHeight, columnWidths, row, font, brush, pen);
                y += rowHeight;
            }
        }
    }

    private void DrawRow(Graphics g, float x, float y, float height, float[] widths, int rowIndex, Font font, Brush brush, Pen pen)
    {
        //// 设置二维码尺寸（占合并单元格80%空间）
        //int qrSize = (int)(widths[3] * 0.8);

        //if (rowIndex == 0)
        //{
        //    // 创建合并单元格区域
        //    RectangleF mergedCell = new RectangleF(x + widths[0] + widths[1] + widths[2], y, widths[3], height * 2);
        //    g.DrawRectangle(pen, mergedCell.X, mergedCell.Y, mergedCell.Width, mergedCell.Height);

        //    // 绘制二维码
        //    if (!string.IsNullOrEmpty(_qrCodeText))
        //    {
        //        using (Bitmap qrCode = GenerateQRCode(_qrCodeText, qrSize, qrSize))
        //        {
        //            // 居中绘制二维码
        //            float qrX = mergedCell.X + (mergedCell.Width - qrSize) / 2;
        //            float qrY = mergedCell.Y + (mergedCell.Height - qrSize) / 2;
        //            g.DrawImage(qrCode, qrX, qrY);
        //        }
        //    }
        //}
        //// 根据行索引应用合并规则
        //switch (rowIndex)
        //{
        //    case 0: // 第一行：合并1列
        //        //DrawMergedCell(g, x, y, widths[0], height, _tableData[rowIndex, 0], font, brush, pen);
        //        //DrawStandardCells(g, x + widths[0], y, height, widths, rowIndex, 1, font, brush, pen);
        //        //break;
        //    case 1: // 第二行：合并2-3列
        //        //DrawStandardCell(g, x, y, widths[0], height, _tableData[rowIndex, 0], font, brush, pen);
        //        //DrawMergedCell(g, x + widths[0], y, widths[1] + widths[2], height, _tableData[rowIndex,1], font, brush, pen);
        //        //DrawStandardCell(g, x + widths[0] + widths[1] + widths[2], y, widths[3], height, _tableData[rowIndex,3], font, brush, pen);
        //        //break;
        //    case 2: // 第三行至第七行：合并2-4列
        //    case 3:
        //    case 4:
        //    case 5:
        //    case 6:
        //        DrawStandardCell(g, x, y, widths[0], height, _tableData[rowIndex,0], font, brush, pen);
        //        DrawMergedCell(g, x + widths[0], y, widths[1] + widths[2] + widths[3], height, _tableData[rowIndex,1], font, brush, pen);
        //        break;
        //    case 7: // 第八行：无合并
        //        DrawStandardCells(g, x, y, height, widths, rowIndex, 0, font, brush, pen);
        //        break;
        //}

        // 设置二维码尺寸（占合并单元格80%空间）
        int qrSize = (int)(widths[3] * 1.3);
        float firstThreeColumnsWidth = widths[0] + widths[1] + widths[2];

        if (rowIndex == 0)
        {
            // 合并第1-3列
            DrawMergedCell(g, x, y, firstThreeColumnsWidth, height, _tableData[rowIndex, 0], font, brush, pen);

            // 创建第4列合并单元格区域（跨两行）
            RectangleF mergedCell = new RectangleF(x + firstThreeColumnsWidth, y, widths[3], height * 2);
            g.DrawRectangle(pen, mergedCell.X, mergedCell.Y, mergedCell.Width, mergedCell.Height);

            // 绘制二维码
            if (!string.IsNullOrEmpty(_qrCodeText))
            {
                using (Bitmap qrCode = GenerateQRCode(_qrCodeText, qrSize, qrSize))
                {
                    // 居中绘制二维码
                    float qrX = mergedCell.X + (mergedCell.Width - qrSize) / 2;
                    float qrY = mergedCell.Y + (mergedCell.Height - qrSize) / 2;
                    g.DrawImage(qrCode, qrX, qrY);
                }
            }
        }
        else if (rowIndex == 1)
        {
            // 合并第1-3列
            DrawMergedCell(g, x, y, firstThreeColumnsWidth, height, _tableData[rowIndex, 0], font, brush, pen);
            // 第4列已在rowIndex=0时合并绘制，此处无需处理
        }
        // 根据行索引应用合并规则
        switch (rowIndex)
        {
            case 2: // 第三行至第七行：合并2-4列
            case 3:
            case 4:
            case 5:
            case 6:
                DrawStandardCell(g, x, y, widths[0], height, _tableData[rowIndex, 0], font, brush, pen);
                DrawMergedCell(g, x + widths[0], y, widths[1] + widths[2] + widths[3], height, _tableData[rowIndex, 1], font, brush, pen);
                break;
            case 7: // 第八行：无合并
                DrawStandardCells(g, x, y, height, widths, rowIndex, 0, font, brush, pen);
                break;
        }
    }

    private void DrawStandardCells(Graphics g, float x, float y, float height, float[] widths, int row, int startCol, Font font, Brush brush, Pen pen)
    {
        float currentX = x;
        for (int col = startCol; col < widths.Length; col++)
        {
            DrawStandardCell(g, currentX, y, widths[col], height, _tableData[row, col], font, brush, pen);
            currentX += widths[col];
        }
    }

    private void DrawStandardCell(Graphics g, float x, float y, float width, float height, string text, Font font, Brush brush, Pen pen)
    {
        g.DrawRectangle(pen, x, y, width, height);
        DrawCenteredText(g, x, y, width, height, text, font, brush);
    }

    private void DrawMergedCell(Graphics g, float x, float y, float width, float height, string text, Font font, Brush brush, Pen pen)
    {
        g.DrawRectangle(pen, x, y, width, height);
        DrawCenteredText(g, x, y, width, height, text, font, brush);
    }

    private void DrawCenteredText(Graphics g, float x, float y, float width, float height, string text, Font font, Brush brush)
    {
        using (StringFormat sf = new StringFormat())
        {
            try
            {
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                g.DrawString(text, font, brush, new RectangleF(x, y, width, height), sf);
            }
            catch (System.Exception ex)
            {
                int i = 0;
            }
        }

        //// 验证绘制区域尺寸
        //if (width <= 0 || height <= 0) return;
        //if (string.IsNullOrEmpty(text)) return;

        //StringFormat format = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
        //RectangleF layoutRectangle = new RectangleF(x, y, width, height);
        //g.DrawString(text, font, brush, layoutRectangle, format);
    }
    }
}
